//
//  AfanOauthController.swift
//  weiboOfAfan
//
//  Created by afan on 16/3/21.
//  Copyright © 2016年 阿范. All rights reserved.
//

import UIKit
import SVProgressHUD

class AfanOauthController: UIViewController {
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavigationBar()
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        let url = NSURL(string: urlString) // 登陆界面的url需要查看api文档
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        
        
        print("\(urlString)")
        // 弹出正在加载的提示
        // showWithStatus,需要主动关闭
        SVProgressHUD.showWithStatus("正在加载", maskType: SVProgressHUDMaskType.None)
        
    }
    //设置导航栏
    private func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }

    
    
    //MARK: 导航栏 item 点击事件
    //自动填充
    @objc private func autoFill() {
        
        let jsCode = "document.getElementById('userId').value='13192330009';document.getElementById('passwd').value='fanzhenghao..'"
        
        // 执行js代码
        webView.stringByEvaluatingJavaScriptFromString(jsCode)
    }
    //关闭
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
        SVProgressHUD.dismiss()
    }
    
    
    //MARK: 懒加载
    private lazy var webView : UIWebView = UIWebView()
}




//MARK: webView 代理
extension AfanOauthController : UIWebViewDelegate{
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL!.absoluteString
//        print("urlString\(urlString)")
        //前缀不是回调地址
        if !urlString.hasPrefix(redirect_uri){
            return true
        }else{
            let query = request.URL?.query
            let codeString = "code="
            
            //点击了授权
            if query!.hasPrefix(codeString){
                let nsQuery = query! as NSString
                let code = nsQuery.substringFromIndex(codeString.characters.count)
                print("code :------\(code)")
                AfanUserAccountViewModel.shardInstace.loadAccessToken(code, completion: { (error) -> () in
                    AppDelegate.outSwitchRootViewController(AfanMainController())
                })
            }else{
                close()
            }
            return false
        }
    }
    

}


























